<template>
  <div class="login">
    <div class="login-content">
      <van-form validate-first @submit="onSubmit">
        <!-- 通过 validator 进行函数校验 -->
        <van-field v-model="username" name="name" placeholder="账号/手机号/邮箱" :rules="[{ required: true, message: '账号错误' }]" />
        <!-- 通过 validator 进行异步函数校验 -->
        <van-field v-model="password" name="pwd" placeholder="请输入密码" :rules="[{ required: true, message: '密码错误' }]" />
        <div style="margin: 16px">
          <van-button round block type="info" native-type="submit" @click="onSubmit">提交</van-button>
        </div>
      </van-form>
    </div>
    <div class="my-divider">
      <a class="register" href="#/register">去注册</a>
      <van-divider>其他的登录方式</van-divider>
    </div>
  </div>
</template>
<script>
import { Toast } from 'vant'
export default {
  created() {
    this.localData = JSON.parse(localStorage.getItem('userData') || '[]')
  },
  data() {
    return {
      username: '',
      password: '',
      localData: []
    }
  },
  methods: {
    onSubmit(values) {
      if (this.localData.length < 1) {
        Toast('请先注册!')
        return
      }
      for (let i = 0; i < this.localData.length; i++) {
        if (this.localData[i].name === values.name && this.localData[i].pwd === values.pwd) {
          Toast('登入成功!')
          localStorage.token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0ZWwiOiIxMzAxMTExMTExMSIsImlhdCI6MTY0OTQwODA1NSwiZXhwIjoxNjUwNzA0MDU1fQ.HUAD3IbCmTcGlWNCKUeG-Pc6pyeQWTCNFzywpXjTWIo'
          this.$router.push('/')
          sessionStorage.setItem('userinfo', JSON.stringify(values))
        } else {
          Toast('登入失败!')
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.login-content {
  button {
    color: white;
    background: rgb(255, 102, 102);
    border-color: rgb(255, 102, 102);
    opacity: 0.5;
  }
}
</style>
